<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="申请人" prop="rtCreatRole">
        <el-input v-model="queryParams.rtCreatRole" placeholder="请输入申请人" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="功能房名" prop="roomName">
        <!-- <el-input v-model="queryParams.roomName" placeholder="请输入功能房名" clearable @keyup.enter.native="handleQuery" /> -->
        <el-select v-model="queryParams.roomName" placeholder="请选择功能房名" @change="handleQuery">
          <el-option v-for="item in roomList" :key="item.roomId" :label="item.roomName"
            :value="item.roomName"></el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="预约时间" prop="rtTime">
        <el-input v-model="queryParams.rtTime" placeholder="请输入预约时间" clearable @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item label="使用状态" prop="rtState">
        <!-- <el-input v-model="queryParams.rtState" placeholder="请输入使用状态" clearable @keyup.enter.native="handleQuery" /> -->
        <el-select v-model="queryParams.rtState" placeholder="请选择使用状态" @change="handleQuery">
          <el-option v-for="item in optionsRtState" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" prop="auditStatus">
        <!-- <el-input v-model="queryParams.auditStatus" placeholder="请输入报名人" clearable @keyup.enter.native="handleQuery" /> -->
        <el-select v-model="queryParams.auditStatus" placeholder="请选择审核状态" @change="handleQuery">
          <el-option v-for="item in optionsAudit" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['staff:roomReservation:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['staff:roomReservation:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['staff:roomReservation:export']">导出</el-button>
      </el-col> -->
      <div style="display: flex; align-items: center;justify-content: space-between;">
        <div style="display: flex; align-items: center;">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
              v-hasPermi="['staff:roomReservation:add']">预约功能房</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
              v-hasPermi="['staff:roomReservation:edit']">修改</el-button>
          </el-col> -->
          <el-col :span="1.5">
            <div style="font-size: 14px;">
              当前显示的是<span style="color: red; font-size: 14px; font-weight: bold;">{{
                switchAuditStatus(queryParams.auditStatus) }}</span>的预约记录
            </div>
          </el-col>
        </div>
        <div>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getUser"></right-toolbar>
        </div>
      </div>
    </el-row>

    <el-table v-loading="loading" :data="roomReservationList" @selection-change="handleSelectionChange" :default-sort = "{prop: 'rtDepar', order: 'ascending'}">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="申请人" align="center" prop="rtCreatRole" />
      <el-table-column label="使用部门/学院" align="center" prop="rtDepar" sortable width="150px"/>
      <el-table-column label="功能房名" align="center" prop="roomName" />
      <el-table-column label="主题" align="center" prop="rtTheme" />
      <el-table-column label="使用期间图片" align="center" prop="rtImgs" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.rtImgs" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="参与人员类型" align="center" prop="rtRole">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.routine_rtfureservation_rt_role" :value="scope.row.rtRole"/>
        </template>
      </el-table-column>
      <el-table-column label="参与人数" align="center" prop="rtPeople" />
      <el-table-column label="预约用途" align="center" prop="rtPurpose">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.routine_rtfureservations_rt_purpose" :value="scope.row.rtPurpose"/>
        </template>
      </el-table-column>
      <el-table-column label="预约时间" align="center" prop="rtTime" />
      <el-table-column label="预约时间段" align="center" prop="rtTimePeriod" />
      <!-- <el-table-column label="创建时间" align="center" prop="rtCreatTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.rtCreatTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="使用状态" align="center" prop="rtState">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.rtState === 0">未使用</el-tag>
          <el-tag type="success" v-else-if="scope.row.rtState === 1">使用中</el-tag>
          <el-tag type="danger" v-else>使用结束</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="auditStatus">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.auditStatus === 0">待审核</el-tag>
          <el-tag type="success" v-else-if="scope.row.auditStatus === 1">通过</el-tag>
          <el-tag type="danger" v-else>不通过</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['staff:roomReservation:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['staff:roomReservation:remove']">删除</el-button> -->
            <el-button size="mini" type="text" icon="el-icon-zoom-in" @click="handleAudit(scope.row, '详情')">查看详情</el-button>
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleAudit(scope.row, '使用结束')"
            v-hasPermi="['staff:roomReservation:edit']" v-if="scope.row.rtState === 2">使用结束反馈</el-button>
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleAudit(scope.row, '审核')"
            v-hasPermi="['staff:roomReservation:edit']" v-else-if="scope.row.auditStatus === 0">审核</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改一站式社区-功能房-预约记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <div style="display: flex;">
        <div style="flex: 1;">
          <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-form-item label="功能房" prop="roomName">
              <el-select v-model="form.roomName" placeholder="请选择功能房" @change="changRoomName" style="width: 100%;">
                <el-option v-for="item in roomList" :key="item.roomId" :label="item.roomName"
                  :value="item.roomName"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="申请人" prop="rtCreatRole">
              <el-input v-model="form.rtCreatRole" placeholder="请输入申请人" />
            </el-form-item>
            <el-form-item label="使用部门/学院" prop="rtDepar">
              <el-input v-model="form.rtDepar" placeholder="请输入使用部门/学院" />
            </el-form-item>
            <el-form-item label="主题" prop="rtTheme">
              <el-input v-model="form.rtTheme" placeholder="请输入主题" />
            </el-form-item>
          </el-form>
        </div>
        <div style="flex: 1;">
          <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-form-item label="参与人员类型" prop="rtRole">
              <el-select v-model="form.rtRole" placeholder="请选择参与人员类型" style="width: 100%;">
                <el-option
                  v-for="dict in dict.type.routine_rtfureservation_rt_role"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="参与人数" prop="rtPeople">
              <!-- <el-input v-model="form.rtPeople" placeholder="请输入参与人数" /> -->
              <el-input-number v-model="form.rtPeople" :min="0" label="请输入参与人数"
              style="width: 100%;"></el-input-number>
            </el-form-item>
            <el-form-item label="预约用途" prop="rtPurpose">
              <el-select v-model="form.rtPurpose" placeholder="请选择预约用途" style="width: 100%;">
                <el-option
                  v-for="dict in dict.type.routine_rtfureservations_rt_purpose"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="预约时间" prop="rtTime">
              <el-input v-model="form.rtTime" placeholder="请输入预约时间(不需要手动输入,选择预约时间会自动填充)" disabled/>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="预约时间段" prop="rtTimePeriod">
          <el-input v-model="form.rtTimePeriod" placeholder="请输入预约时间段(不需要手动输入,选择预约时间段会自动填充)" disabled/>
        </el-form-item>
        <el-form-item label="预约时间">
          <template slot-scope="scope">
            <div style="display: flex; flex-wrap: wrap;">
              <div v-for="(item, index) in getCombinedWeekDates()" :key="item.date" style="margin-right: 10px; cursor: pointer;" :class="`${activateDateIndex === item.date ? 'activate' : 'unactivated'}`" @click="activateDate(item.date, item.week)">
                {{ item.date }}
              </div>
            </div>
          </template>
        </el-form-item>
        <el-form-item label="选择预约时间">
          <!-- <el-table :data="tableData" border style="width: 100%">
            <el-table-column prop="setTime" label="设置时间" align="center">
            </el-table-column>
            <el-table-column v-for="item in tableData.weekday" :label="item.day" align="center">
            </el-table-column>
          </el-table> -->
          <div class="timetable">
            <table>
              <thead>
                <tr>
                  <th style="text-align: center;">星期</th>
                  <th style="text-align: center;">时间（如果表格没显示时间，就代表该日期没有可预约的时间段）</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(time, index) in times" :key="index">
                  <td style="width: 80px; text-align: center; background-color: #1890ff; color: white;">
                    {{ weekdays[index] }}
                  </td>
                  <td>
                    <div style="display: flex; flex-wrap: wrap; align-items: center;">
                      <div v-for="(item, i) in time" :key="i" :class="`${item.isDel !== 0 ? '' : 'timeBox'}`"
                        @mouseenter="item.isHovered = true" @mouseleave="item.isHovered = false">
                        <div style="display: flex;align-items: center;">
                          <el-button
                            :style="shouldDisableButton(weekdays[index], item.value, item.valueEnd, item.isOccupy) ? 'border: 1px solid #ddd;color: #bdbdbd;' : ''"
                            :disabled="shouldDisableButton(weekdays[index], item.value, item.valueEnd, item.isOccupy)"
                            :class="`${activateId === item.ohId ? 'activate' : 'unactivated'}`"
                            @click="activateTime(item.ohId, item.value, item.valueEnd, weekdays[index], item.rtNo)">
                            {{ item.value }} ~ {{ item.valueEnd }}
                          </el-button>
                        </div>
                      </div>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </el-form-item>
        <el-form-item label="使用期间图片" prop="rtImgs">
          <image-upload v-model="form.rtImgs" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 审核 -->
    <el-dialog :title="handleAuditTitle" :visible.sync="openAudit" width="800px" append-to-body>
      <div v-if="handleAuditTitle === '审核'">
        <div style="display: flex;">
          <div style="flex: 1">
            <el-form ref="form" :model="form" :rules="rules" label-width="120px">
              <el-form-item label="主题" prop="rtTheme">
                <el-input v-model="form.rtTheme" placeholder="请输入主题" disabled/>
              </el-form-item>
              <el-form-item label="参与人员类型" prop="rtRole">
              <el-select v-model="form.rtRole" placeholder="请选择参与人员类型" style="width: 100%;" disabled>
                <el-option
                  v-for="dict in dict.type.routine_rtfureservation_rt_role"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            </el-form>
          </div>
          <div style="flex: 1; margin-left: 10px;">
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
              <el-form-item label="参与人数" prop="rtPeople">
                <el-input v-model="form.rtPeople" placeholder="请输入参与人数" disabled/>
              </el-form-item>
              <el-form-item label="预约用途" prop="rtPurpose">
              <el-select v-model="form.rtPurpose" placeholder="请选择预约用途" style="width: 100%;" disabled>
                <el-option
                  v-for="dict in dict.type.routine_rtfureservations_rt_purpose"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            </el-form>
          </div>
        </div>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="审核状态" prop="auditStatus">
            <el-radio-group v-model="form.auditStatus">
              <el-radio :label="0" disabled>待审核</el-radio>
              <el-radio :label="1">通过</el-radio>
              <el-radio :label="2">不通过</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="修改意见" prop="editOpinion" v-if="form.auditStatus === 2">
            <el-input v-model="form.editOpinion" type="textarea" rows="5" placeholder="请输入内容" />
          </el-form-item>
        </el-form>
      </div>
      <div v-else-if="handleAuditTitle === '使用结束'">
        <!-- <img :src="imgUrl + form.rtImgs" alt="活动图片" width="350px"> -->
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="活动结束反馈" prop="feedback">
            <el-input v-model="form.feedback" type="textarea" rows="5" placeholder="请输入内容" />
          </el-form-item>
        </el-form>
      </div>
      <div v-else>
        <div style="position: relative;">
          <h2 style="text-align: center;">预约信息</h2>
          <p>功能房名称：{{ form.roomName }}</p>
          <p>预约时间段：{{ form.rtTimePeriod }}</p>
          <p>预约用途： {{ form.rtPurpose }}</p>
          <p>申请人： {{ form.rtCreatRole }}</p>
          <p>使用部门/学院： {{ form.rtDepar }}</p>
          <p>
            使用状态： <span v-if="form.rtState === 0" class="status-unused">{{ stateTexts[form.rtState] }}</span>
            <span v-else-if="form.rtState === 1" class="status-in-use">{{ stateTexts[form.rtState] }}</span>
            <span v-else class="status-ended">{{ stateTexts[form.rtState] }}</span>
          </p>
          <p>
            审核状态：
            <span v-if="form.auditStatus === 0" class="status-unused">{{ auditTexts[form.auditStatus] }}</span>
            <span v-else-if="form.auditStatus === 1" class="status-in-use">{{ auditTexts[form.auditStatus] }}</span>
            <span v-else class="status-ended">{{ auditTexts[form.auditStatus] }}</span>
          </p>
          <!-- <div class="box">使用</div> -->
        </div>
      </div>
      <div slot="footer" class="dialog-footer" v-if="handleAuditTitle === '审核' || handleAuditTitle === '使用结束'">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRoomReservation, getRoomReservation, delRoomReservation, addRoomReservation, updateRoomReservation, getRoomByRoomNoAndTime } from "@/api/staff/roomReservation";
import { listRoomAll } from "@/api/staff/room";
import { getUserProfile } from "@/api/system/user"; // 获取当前用户接口
export default {
  name: "RoomReservation",
  dicts: ['routine_rtfureservation_rt_role', 'routine_rtfureservations_rt_purpose'],
  data() {
    return {
      imgUrl: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 一站式社区-功能房-预约记录表格数据
      roomReservationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openAudit: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        rtNo: null,
        roomNo: null,
        roomName: null,
        rtTheme: null,
        rtRole: null,
        rtPeople: null,
        rtPurpose: null,
        rtTime: null,
        rtTimePeriod: null,
        rtState: null,
        rtImgs: null,
        rtCreatTime: null,
        rtUpTime: null,
        rtCreatRole: null,
        rtDepar: null,
        auditStatus: 0
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        roomName: [
          { required: true, message: "功能房名不能为空", trigger: "change" }
        ],
        rtTheme: [
          { required: true, message: "主题不能为空", trigger: "blur" }
        ],
        rtRole: [
          { required: true, message: "参与人员类型不能为空", trigger: "blur" }
        ],
        rtPeople: [
          { required: true, message: "参与人数不能为空", trigger: "blur" }
        ],
        rtPurpose: [
          { required: true, message: "预约用途不能为空", trigger: "blur" }
        ],
        rtTimePeriod: [
          { required: true, message: "预约时间段不能为空", trigger: "blur" }
        ],
        rtTime: [
          { required: true, message: "预约时间不能为空", trigger: "blur" }
        ],
        rtCreatRole: [
          { required: true, message: "申请人不能为空", trigger: "blur" }
        ],
        rtDepar: [
          { required: true, message: "借用部门、学院不能为空", trigger: "blur" }
        ],
      },
      optionsAudit: [ // 下拉选项数组
        { value: null, label: '全部' },
        { value: 0, label: '待审核' },
        { value: 1, label: '同意' },
        { value: 2, label: '不同意' }
      ],
      optionsRtState: [ // 下拉选项数组
        { value: null, label: '全部' },
        { value: 0, label: '未使用' },
        { value: 1, label: '使用中' },
        { value: 2, label: '使用结束' }
      ],
      roomList: [],
      weekdays: [
        '星期一',
        '星期二',
        '星期三',
        '星期四',
        '星期五',
        '星期六',
        '星期日'
      ],
      times: [
        [{ value: '08:00', valueEnd: '09:00', isHovered: false }, { value: '08:00', valueEnd: '12:00', isHovered: false }], // 星期一
        [], // 星期二
        [{ value: '09:00', valueEnd: '10:00', isHovered: false }], // 星期三
        [], // 星期四
        [{ value: '09:00', valueEnd: '10:30', isHovered: false }], // 星期五
        [{ value: '10:00', valueEnd: '12:00', isHovered: false }], // 星期六
        []      // 星期日（根据图片，星期日没有预设时间）
      ],
      // 开放时间段标识
      activateId: null,
      // 开放时间下标
      activateDateIndex: null,
      handleAuditTitle: null,
      stateTexts: {
        '0': '未使用',
        '1': '使用中',
        '2': '使用结束'
      },
      auditTexts: {
        '0': '待审核',
        '1': '通过',
        '2': '不通过'
      },
      // 记录选择的时间是否是本周
      weekData: null
    };
  },
  watch: {
    "$route.query.roomNo": {
      immediate: true,
      handler() {
        this.queryParams.roomNo = null
        this.reset()
        if (this.$route.query.roomNo !== undefined) {
          if (this.$route.query.roomNo !== null) {
            this.queryParams.roomNo = this.$route.query.roomNo
            this.getUser()
            return
          }
          this.queryParams.roomNo = null
          this.reset()
        } else {
          this.queryParams.roomNo = null
          this.getUser()
          this.reset()
        }
      }
    }
  },
  created() {
    // this.getList();
  },
  methods: {
    // 获取当前登录信息
    getUser() {
      this.loading = true;
      getUserProfile().then((response) => {
        // this.user = response.data;
        // this.roleGroup = response.roleGroup;
        // this.postGroup = response.postGroup;
        // console.log(response);
        if (!response.roleGroup.includes("超级管理员")) {
          this.queryParams.rtCreatRole = response.data.nickName;
          this.getList();
          return;
        }
        this.loading = false;
        this.getList();
      });
    },
    /** 查询一站式社区-功能房-预约记录列表 */
    getList() {
      this.loading = true;
      listRoomReservation(this.queryParams).then(response => {
        this.roomReservationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      // 功能房列表
      listRoomAll().then(response => {
        this.roomList = response.data
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openAudit = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        rtId: null,
        rtNo: null,
        roomNo: null,
        roomName: null,
        rtTheme: null,
        rtRole: null,
        rtPeople: null,
        rtPurpose: null,
        rtTime: null,
        rtTimePeriod: null,
        rtState: null,
        rtImgs: null,
        rtCreatTime: null,
        rtUpTime: null,
        rtCreatRole: null,
        rtDepar: null,
        auditStatus: null
      };
      // 遍历times数组，并清空每个子数组
      this.times.forEach(day => {
        day.length = 0; // 清空子数组
      })
      this.activateId = null
      this.activateDateIndex = null
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.rtId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加一站式社区-功能房-预约记录";
    },
    // 打开审核对话框
    handleAudit(row, text) {
      this.openAudit = true
      let data = JSON.stringify(row)
      this.form = JSON.parse(data)
      this.handleAuditTitle = text
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const rtId = row.rtId || this.ids
      getRoomReservation(rtId).then(response => {
        this.form = response.data;

        // 先判断this.form.rtTime时间是本周还是下周的
        let week = null
        this.getCombinedWeekDates().forEach(element => {
          if (element.date === this.form.rtTime) {
            week = element.week
          }
        });
        // 处理对应功能房的预约规则时间，转换成页面显示的时间段
        this.activateDate(this.form.rtTime, week)
        // 默认选择已预约的时间段
        this.activateId = this.form.staffOneStopRoomOpeningHoursList[0].ohId
        this.open = true;
        this.title = "修改一站式社区-功能房-预约记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 检查表单中是否有空字符串
          let hasEmptyString = Object.values(this.form).some(value => {
            return (value !== null && value !== undefined && (typeof value === 'string' ? value.trim() === '' : false));
          });

          if (hasEmptyString) {
            this.$modal.msgError("表单中存在空字符串，请填写完整");
            return;
          }
          if (this.form.rtId != null) {
            // 如果审核同意的话，使用状态改成使用中，功能房预约时间段占用
            if (this.handleAuditTitle == '审核') {
              if (this.form.auditStatus === 1) {
                this.form.rtState = 1
                // this.form.staffOneStopRoomOpeningHoursList[0].isOccupy = 1
              }
            }
            updateRoomReservation(this.form).then(response => {
              this.$modal.msgSuccess(this.handleAuditTitle === '审核' ? "审核成功" : "修改成功");
              this.open = false;
              this.openAudit = false
              this.getList();
            });
          } else {
            addRoomReservation(this.form).then(response => {
              if (response.code == 200) {
                this.$modal.msgSuccess("预约成功");
                this.getList();
              }
              this.open = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const rtIds = row.rtId || this.ids;
      this.$modal.confirm('是否确认删除一站式社区-功能房-预约记录编号为"' + rtIds + '"的数据项？').then(function () {
        return delRoomReservation(rtIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('staff/roomReservation/export', {
        ...this.queryParams
      }, `roomReservation_${new Date().getTime()}.xlsx`)
    },
    // 预约功能房名称下拉选择，选择到对应的功能房
    changRoomName() {
      let data = this.roomList.filter(item => item.roomName == this.form.roomName)
      if (data.length > 0) {
        // 获取功能房编号
        this.form.roomNo = data[0].roomNo
        // if (data[0].staffOneStopRoomOpeningHoursList != 0) {
        //   this.times = this.revertDataToOriginalFormat(data[0].staffOneStopRoomOpeningHoursList)
        // }
      } else {
        console.log("没有找到匹配的活动");
        // 可以在这里处理没有找到匹配活动的情况
      }
    },
    // 选择预约时间
    activateDate(date, week) {
      if (this.form.roomNo === null) {
        this.$modal.msgError("请先选择功能房");
        return
      }
      this.$modal.loading("正在努力加载中，请稍等。。。");
      this.activateDateIndex = date
      // 设置预约时间
      this.form.rtTime = date
      this.weekData = week
      getRoomByRoomNoAndTime({roomNo: this.form.roomNo, rtTime: date}).then(res => {
        this.times = this.revertDataToOriginalFormat(res.data)
        this.$modal.closeLoading();
      })
    },
    // 选择开放的时间段
    activateTime(ohId, value, valueEnd, weekdays, rtNo) {
      this.activateId = ohId
      // 设置预约时间
      // this.form.rtTime = this.getNextWeekday(weekdays)
      // 设置预约时间段
      this.form.rtTimePeriod = `${value + '~' + valueEnd}`
      // 获取功能房预约时间段编号
      this.form.rtNo = rtNo
    },
    // 将数据来源的时间段数组转化成页面显示的时间段
    revertDataToOriginalFormat(modifiedData) {
      // 创建一个空对象来按星期几存储时间段
      const originalFormat = {};

      // 遍历修改后的数据
      modifiedData.forEach(item => {
        // 确保originalFormat中有对应星期几的数组
        if (!originalFormat[item.ohWeekday]) {
          originalFormat[item.ohWeekday] = [];
        }

        // 将openingHours拆分为value和valueEnd，并添加到对应星期几的数组中
        const [value, valueEnd] = item.openingHours.split('-');
        const time = { value, valueEnd, isHovered: item.isHovered, roomNo: item.roomNo, ohId: item.ohId, isDel: 0, rtNo: item.rtNo, isOccupy: item.isOccupy };
        originalFormat[item.ohWeekday].push(time);
      });

      // 将对象转换为按星期几排序的数组（如果需要的话）
      // 注意：由于weekdays数组已经定义了顺序，我们可以直接使用它
      // const weekdays = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'];
      const sortedData = this.weekdays.map(day => originalFormat[day] || []); // 如果某天没有数据，则返回空数组

      return sortedData;
    },
    // 根据当前时间和给出的星期几（例如，“星期一”），来找出下一个对应的星期几的日期，用来显示（表单中的预约时间段）
    getNextWeekday(weekdayStr) {
      // 定义一个数组来映射星期几的字符串到getDay()方法的返回值
      const weekdays = {
        '星期日': 0,
        '星期一': 1,
        '星期二': 2,
        '星期三': 3,
        '星期四': 4,
        '星期五': 5,
        '星期六': 6
      };

      // 将输入的星期几字符串转换为数字
      const targetDay = weekdays[weekdayStr.substring(0, 1).toUpperCase() + weekdayStr.substring(1).toLowerCase()];

      // 获取当前日期
      let today = new Date();

      // 计算今天是星期几
      let todayDay = today.getDay();

      // 如果今天就是目标星期几，则直接返回今天的日期
      if (todayDay === targetDay) {
        return formatDate(today);
      }
      // 否则，计算需要减少或增加的天数以到达本周的目标星期几
      else {
        // 使用模运算和负数来处理星期的差异
        let daysToAdd = (targetDay - todayDay + 7) % 7;
        // 如果daysToAdd是0，说明是下一周的目标星期几，但我们需要本周的，所以减7
        if (daysToAdd === 0) {
          daysToAdd -= 7;
        }
        // 注意：因为今天是目标日之前，所以我们用加法（虽然实际上是减少天数）
        today.setDate(today.getDate() + daysToAdd);
        return formatDate(today);
      }

      // 辅助函数：格式化日期为 YYYY-MM-DD
      function formatDate(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      }
    },
    // 判断预约时间是否符合，小于当天不能预约，在当天还要根据指定的时间范围判断是否能预约，大于当天则可以预约
    shouldDisableButton(weekdayStr, value, valueEnd, isOccupy) {
      // 如果选择的日期是下周的，全部开放
      if (this.weekData === '下周') {
        // 如果下周的时间有被预约的，禁用
        if (isOccupy === 1) {
          return true
        }
        return false
      }
      // 如果该时间段被使用，直接禁用
      if (isOccupy === 1) {
        return true
      }
      const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
      const today = new Date();
      const todayWeekdayIndex = today.getDay(); // 获取今天星期几的索引（0-6）
      const targetWeekdayIndex = weekdays.indexOf(weekdayStr.toLowerCase()); // 获取目标星期几的索引

      // 将时间字符串转换为分钟表示
      const startTimeMinutes = parseInt(value.split(':')[0], 10) * 60 + parseInt(value.split(':')[1], 10);
      const endTimeMinutes = parseInt(valueEnd.split(':')[0], 10) * 60 + parseInt(value.split(':')[1], 10);
      const nowMinutes = today.getHours() * 60 + today.getMinutes(); // 获取当前时间的分钟表示

      // 检查是否是同一个星期几
      if (todayWeekdayIndex === targetWeekdayIndex) {
        // 如果还没到开始时间，则不禁用
        if (nowMinutes < startTimeMinutes) {
          return false
        }
        // 如果是目标星期几，检查当前时间是否在指定时间范围内
        return nowMinutes < startTimeMinutes || nowMinutes > endTimeMinutes;
      }

      // 处理星期日的特殊逻辑
      if (targetWeekdayIndex === 0) {
        // 如果目标星期几是星期日，检查是否已经过了一周的周期
        // 这里我们假设一周的结束时间是周一的开始时间，即00:00
        // const nextMondayMinutes = (today.getHours() === 0 && today.getMinutes() === 0) ? 0 : 24 * 60;
        return false;
      }

      // 如果当前是星期日，其他全部禁用
      if (todayWeekdayIndex === 0) {
        return true
      }

      // 如果当前星期几小于目标星期几，且目标星期几不是星期日
      return todayWeekdayIndex > targetWeekdayIndex;
    },
    // 按审核状态搜索，显示对应的文字
    switchAuditStatus(status) {
      return this.optionsAudit.filter(item => item.value === status)[0].label
    },
    // 根据系统时间获取本周和下周的日期
    getCombinedWeekDates() {
      function formatDate(date) {
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 月份需要加1，且保证至少两位数字
        const day = date.getDate().toString().padStart(2, '0'); // 日期保证至少两位数字
        return `${year}-${month}-${day}`;
      }
      const today = new Date(); // 获取当前日期
      const startDay = today.getDay(); // 获取今天是周几
      const weekStart = 1; // 一周的开始是周一

      // 计算本周的第一天（周一）
      const startDateThisWeek = new Date(today);
      startDateThisWeek.setDate(today.getDate() - startDay + weekStart);

      // 初始化日期数组
      const combinedDates = [];

      // 循环添加本周和下周的日期
      for (let i = 0; i < 14; i++) {
        const date = new Date(startDateThisWeek);
        date.setDate(date.getDate() + i);
        const week = i < 7 ? '本周' : '下周';
        combinedDates.push({
          date: formatDate(date), // 使用辅助函数格式化日期
          week: week
        });
      }

      return combinedDates;
    }
  }
};
</script>

<style scoped>
.timetable table {
  width: 100%;
  border-collapse: collapse;
}

.timetable th,
.timetable td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

.timetable th {
  background-color: #f2f2f2;
}

input[type="time"] {
  width: 70px;
  border: 0;
  /* Adjust the width as needed */
}

.timeBox {
  position: relative;
  max-width: 200px;
  padding: 10px;
}

.timeBox i {
  position: absolute;
  right: 0;
  top: 0;
}

.unactivated {
  border: 1px solid #1890ff;
  border-radius: 10px;
  color: #1890ff;
  background-color: white;
  padding: 10px 15px;
  margin: 5px 5px;
}

.activate {
  border: 1px solid #1890ff;
  background-color: #1890ff;
  border-radius: 10px;
  color: white;
  padding: 10px 15px;
  margin: 5px 5px;
}

.box {
  position: absolute;
  top: 0;
  right: 0;
}

/* 定义不同状态的颜色类 */
.status-unused {
  color: #1890ff; /* 未使用，灰色 */
}

.status-in-use {
  color: rgb(0, 255, 30); /* 使用中，蓝色 */
}

.status-ended {
  color: red; /* 使用结束，红色 */
}
</style>